

const musicEl = document.querySelector('.music-element');
const playBtn = document.querySelector('.play');
const seekBar = document.querySelector('.seekbar');
const currentTime = document.querySelector('.current-time');
const duration = document.querySelector('.duration');
const volumeBtn = document.querySelector('.volume-btn');
const playEl = document.querySelector('.play i');
const repeat = document.querySelector('.btn-box .repeat');
const favourte = document.querySelector('.btn-box .favourte');
const volume = document.querySelector('.btn-box .volume');
const volumeBox = document.querySelector('.volume-box');
const volumeRange = document.querySelector('.volume-box .volume-range');
const volumeDown = document.querySelector('.volume-box .volume-down');
const volumeUp = document.querySelector('.volume-box .volume-up');

function handlePlay () {
  if (musicEl.paused) {
    // 改为播放
    musicEl.play();
    playEl.classList.replace('icon-bofang2', 'icon-zanting');
  } else {
    musicEl.pause();
    playEl.classList.replace('icon-zanting', 'icon-bofang2');
  }
}

function formatTime(currentTime) {
  const s = parseInt(currentTime % 60) + '';
  const m = parseInt(currentTime / 60 % 60) + '';
  return`${m.padStart(2, '0')}:${s.padStart(2, '0')}`
}

// 循环播放
function handleRepeat() {
  if (musicEl.loop) {
    repeat.classList.remove('active');
    musicEl.loop = false;
  } else {
    repeat.classList.add('active');
    musicEl.loop = true;
  }
}

// 点击收藏
function handleFavourite() {
  favourte.classList.toggle('active');
}

// 设置音量
function handleVolume() {
  volume.classList.toggle('active');
  volumeBox.classList.toggle('active');
}

// 监听音乐加载完成，更新音乐总时间
musicEl.addEventListener('loadeddata', function () {
  seekBar.max = musicEl.duration;
  duration.innerHTML = formatTime(musicEl.duration)
})

// 监听音乐播放完毕
musicEl.addEventListener('ended', function () {
  playEl.classList.replace('icon-zanting', 'icon-bofang2');
  musicEl.currentTime = 0
})

// 音乐播放的时间同步到进度条上
musicEl.addEventListener('timeupdate', function () {
  seekBar.value = musicEl.currentTime;
  currentTime.innerHTML = formatTime(musicEl.currentTime)
})

// 拖动进度条
function handleSeekBar() {
  musicEl.currentTime = seekBar.value;
}

// 增大音量
function handleVolumeUp(params) {
  // 将音量滑动条的值增大20
  volumeRange.value = parseInt(volumeRange.value) + 20;
  // if (volumeRange.value > 100) {
  //   volumeRange.value = 100;
  // }
  // 将音乐的音量设置为滑动条的值/100
  musicEl.volume = volumeRange.value / 100;
}
// 减小音量
function handleVolumeDown(params) {
    // 将音量滑动条的值增大20
    volumeRange.value = parseInt(volumeRange.value) - 20;
    // if (volumeRange.value < 0) {
    //   volumeRange.value = 0;
    // }
    // 将音乐的音量设置为滑动条的值/100
    musicEl.volume = volumeRange.value / 100;
}

volumeUp.addEventListener('click', handleVolumeUp)
volumeDown.addEventListener('click', handleVolumeDown)
